package com.eyas.im.gui.swing.index;

import com.eyas.im.common.datasource.DataSourceUtils;
import com.eyas.im.gui.swing.common.CommonUtils;
import com.eyas.im.gui.swing.login.Session;
import com.eyas.im.gui.swing.login.dao.IMUserInfo;
import com.eyas.im.server.IMServer;
import com.eyas.im.server.nio.NIOIMServer;
import com.eyas.im.server.nio.NioServerConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

import static java.awt.GridBagConstraints.EAST;

public class FriendListFrame extends JFrame implements WindowListener, ActionListener, MouseListener {
    private final static Logger logger = LoggerFactory.getLogger(FriendListFrame.class);
    private static FriendListFrame friendListFrame;
    private static boolean initialFlag = false;
    private JList<IMUserInfo> friendsList;
    private DefaultListModel<IMUserInfo> friendInfo = new DefaultListModel<>();
    private JLabel friendsNumLable;
    private IMServer imServer;

    public static FriendListFrame getInstance() {
        if(!initialFlag) {
            synchronized (FriendListFrame.class) {
                if(!initialFlag) {
                    friendListFrame = new FriendListFrame();
                    initialFlag = true;
                }
            }
        }

        return friendListFrame;
    }

    private FriendListFrame() {
        this.initial();
        this.addWindowListener(this);
    }

    /**
     * 初始化环境，主要分为两部分
     * 1、UI部分的信息加载
     * 2、启动IMServer用于监听到来的请求
     */
    private void initial() {
        this.initialServerSocket();
        this.initialFrame();
    }

    private void initialServerSocket() {
        NioServerConfiguration nioServerConfiguration = new NioServerConfiguration();
        nioServerConfiguration.setHostname("0.0.0.0");
        nioServerConfiguration.setPort(0);
        nioServerConfiguration.setHandlerClass(JFrameServerHandler.class);
        this.imServer = new NIOIMServer("0.0.0.0",0);
        Thread IMServerExecutor = new Thread(()->{
            try {
                FriendListFrame.this.imServer.startUp();
            } catch (IOException e) {
                logger.error("IM Server服务启动失败",e);
                JOptionPane.showMessageDialog(FriendListFrame.this,"IM Server服务启动失败");
                FriendListFrame.this.dispose();
            }
        },"IM-SERVER-EXECUTOR");
        IMServerExecutor.start();
    }

    private void initialFrame() {
        this.setResizable(false);
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        this.setPreferredSize(new Dimension(300,600));
        this.addComponent();
        this.pack();
        Dimension screenSzie = Toolkit.getDefaultToolkit().getScreenSize();
        double x = screenSzie.getWidth();
        Dimension frameSize = this.getSize();
        double fx = frameSize.getWidth();
        this.setLocation((int)(x-fx-100),50);
        this.setVisible(true);
    }

    private void addComponent() {
        JPanel mainPanel = new JPanel();
        GridBagLayout gridBagLayout = new GridBagLayout();
        mainPanel.setLayout(gridBagLayout);
        Font fontBlod20 = new Font("",Font.BOLD,20);

        this.friendsList = new JList<>(this.friendInfo);
        this.friendsList.setVisibleRowCount(10); //一屏中最多显示10个好友
        this.friendsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //一次只能选择一个好友
        this.friendsList.addMouseListener(this);
        this.friendsList.setFont(fontBlod20);
        JScrollPane friendsScrollPane = new JScrollPane(friendsList,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        friendsScrollPane.setPreferredSize(new Dimension(240,400));

        JButton addFriendButton = new JButton("+");
        addFriendButton.setToolTipText("添加好友");
        addFriendButton.setActionCommand(FriendManagerFrame.ADD_FRIEND_ACTION);
        addFriendButton.addActionListener(this);
        addFriendButton.setFont(fontBlod20);

        JButton removeFriendButton = new JButton("-");
        removeFriendButton.setToolTipText("删除好友");
        removeFriendButton.addActionListener(this);
        removeFriendButton.setActionCommand(FriendManagerFrame.REMOVE_FRIEND_ACTION);
        removeFriendButton.setFont(fontBlod20);


        //查询好友列表
        int friendsNum = this.queryFriendsList();

        friendsNumLable = new JLabel("好友数量:"+friendsNum);
        friendsNumLable.setFont(fontBlod20);

        //开始画窗口布局
        GridBagConstraints gridBagConstraints = new GridBagConstraints();

        CommonUtils.resetGridBagConstraints(gridBagConstraints);
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = EAST;
        gridBagConstraints.insets = new Insets(10,5,5,10);
        mainPanel.add(friendsNumLable,gridBagConstraints);

        CommonUtils.resetGridBagConstraints(gridBagConstraints);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.insets = new Insets(10,5,5,10);
        mainPanel.add(friendsScrollPane,gridBagConstraints);

        CommonUtils.resetGridBagConstraints(gridBagConstraints);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.insets = new Insets(10,5,5,10);
        mainPanel.add(addFriendButton,gridBagConstraints);

        CommonUtils.resetGridBagConstraints(gridBagConstraints);
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.insets = new Insets(10,5,5,10);
        mainPanel.add(removeFriendButton,gridBagConstraints);

        this.add(mainPanel);
    }

    /**
     * 查询好友列表
     * @return 返回有效的好友总数
     */
    private int queryFriendsList() {
        try {
            java.util.List<IMUserInfo> friendInfoList = DataSourceUtils.INSTANCE.query("select c.USERID,c.USERACCOUNT,c.USERPASSWORD " +
                            " from IM_USER_INFO a,IM_FRIEND_LIST_INFO b,IM_USER_INFO c " +
                            " where a.userid=b.USERID and a.USERID = ? and b.FRIENDID=c.USERID and b.FRIENDSTATE='1' " +
                            " and c.VALIDFLAG='1' order by b.flpkid",
                    IMUserInfo.class, Session.CURRENT_USER_INFO.getUserId());
            if(friendInfoList!=null) {
                friendInfoList.forEach(imFriendListInfo -> {
                    FriendListFrame.this.friendInfo.addElement(imFriendListInfo);
                });
            }
            return friendInfoList==null?0:friendInfoList.size();
        } catch (Exception e) {
            logger.error("查询好友列表失败",e);
            JOptionPane.showMessageDialog(this,"查询好友列表失败");
        }
        return 0;
    }

    @Override
    public void windowOpened(WindowEvent e) {

    }

    @Override
    public void windowClosing(WindowEvent e) {
        this.dispose();
    }

    @Override
    public void windowClosed(WindowEvent e) {
        logger.debug("关闭即使通讯服务");
        this.imServer.shudownGraceful();
        logger.debug("关闭IM Server服务结束");
        CommonUtils.destoryApp();
        logger.debug("关闭其他系统资源结束");
    }

    @Override
    public void windowIconified(WindowEvent e) {

    }

    @Override
    public void windowDeiconified(WindowEvent e) {

    }

    @Override
    public void windowActivated(WindowEvent e) {

    }

    @Override
    public void windowDeactivated(WindowEvent e) {

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        switch (e.getActionCommand()) {
            case FriendManagerFrame.ADD_FRIEND_ACTION:
                //新增好友
                new FriendManagerFrame(FriendManagerFrame.ADD_FRIEND_ACTION,this);
                break;
            case FriendManagerFrame.REMOVE_FRIEND_ACTION:
                //删除好友
                new FriendManagerFrame(FriendManagerFrame.REMOVE_FRIEND_ACTION,this);
                break;
            default:
                JOptionPane.showMessageDialog(this,"不支持的操作:"+e.getActionCommand());
                break;
        }
    }

    public void addFriend(IMUserInfo friendInfo) {
        this.friendInfo.addElement(friendInfo);
        this.friendsList.ensureIndexIsVisible(this.friendInfo.size()-1);
        this.friendsNumLable.setText("好友数量::"+this.friendInfo.size());
    }

    public void removeFriend(IMUserInfo imUserInfo) {
        assert  imUserInfo!=null;
        this.friendInfo.removeElement(imUserInfo);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if(e.getClickCount()==2&&this.friendsList.getSelectedIndex()>-1) {
            System.out.println(this.friendInfo.get(this.friendsList.getSelectedIndex()).getUserAccount());
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

}
